// pages/classify/classify.js
const app = getApp()
const pool = new Map()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        status: 'DEFAULT',
        sort: 'ASC',
        loading: false,
        num: 1,
        category: [],
        sortTab: [{
                name: '综合排序',
                status: 'DEFAULT'
            },
            {
                name: '按价格',
                status: 'PRICE'
            },
            {
                name: '销量',
                status: 'SELL'
            },
        ],
        is_supermarket: true,                                                                                    
        f_default_index: 0,
    },
    onLoad: function(options) {
        wx.showLoading({
            title: '加载中...',
        })
    },
    onShow() {
        let cid = wx.getStorageSync('cid')
        this.setData({
            cid,
        })
		pool.clear()
        this.loadCategory()
    },
    loadCategory() {
        if (this.data.loading) return
        this.setData({
            loading: true
        })
        app.http.get('category/supermarket', {
            data: {
                cid: this.data.cid
            }
        }).then(res => {
            wx.hideLoading()
            this.setData({
                loading: false,
                category: res.data,
                is_supermarket: res.data.length != 0
            })
            if (!this.data.is_supermarket) return
            this.menuClick({
                currentTarget: {
                    dataset: {
                        id: this.data.category[this.data.f_default_index].category_id,
                        index:this.data.f_default_index
                    }
                }
            })
        }).catch(err => {
            wx.hideLoading()
            this.setData({
                loading: false
            })
            console.log(err, 'xxxx')
            app.wxToast.error(err.message);
        })
    },

    tab() {
        if (!pool.has(this.data.child_id)) {
            pool.set(this.data.child_id, {
                page: 1,
                nextPage: true,
                loading: false,
                list: []
            })
        }
        return pool.get(this.data.child_id)
    },
    loadGoods() {
        const tab = this.tab()
        this.setData(tab)
        if (tab.loading || !tab.nextPage || !this.data.cid) {
            wx.stopPullDownRefresh()
            return
        }
        this.setData({
            loading: true
        })
        app.http.get("supermarket/list", {
            data: {
                cid: this.data.cid,
                page: tab.page,
                category_id_1: 1,
                category_id_2: this.data.category_id,
                category_id_3: this.data.category_id == this.data.child_id ? 0 : this.data.child_id,
                sort: this.data.status,
                sort_type: this.data.sort
            }
        }).then(res => {
            tab.page++
            tab.loading = false
            tab.nextPage = res.data.nextPage
            tab.list.push(...res.data.list)
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
        }).catch(err => {
            this.setData({
                loading: false,
            })
        })
    },
    loadMore() {
        this.loadGoods()
    },
    // loadList() {
    //     const tab = this.tab()
    //     tab.page = 1
    //     tab.loading = false
    //     tab.nextPage = true
    //     tab.list = []
    //     this.setData(tab)
    //     this.loadGoods()
    // },
    clickChildCategory(evt) {
        let child_id = evt.currentTarget.dataset.id
        this.setData({
            child_id,
        })
        this.loadGoods()
    },
    menuClick: function(evt) {
        let index = evt.currentTarget.dataset.index
        let category_id = evt.currentTarget.dataset.id
        let currentCate = this.data.category.find(o => o.category_id == category_id)
        this.setData({
            category_id,
            f_default_index: index,
            childCategory: currentCate.child.length != 0 ? [{
                category_id: category_id,
                name: '全部'
            }].concat(currentCate.child) : []
        })
        console.log(this.data.f_default_index, typeof this.data.f_default_index)
        this.clickChildCategory({
            currentTarget: {
                dataset: {
                    id: this.data.childCategory[0].category_id,
                }
            }
        })
    },
    //加入购物车
    joinCart(evt) {
        let {
            goodsid,
            index
        } = evt.currentTarget.dataset
        let specList = this.data.list[index].sku
        this.setData({
            specList,
            showSpec: specList ? true : false,
            currentGoodsIndex: index
        });
        !specList && this.submitSpec({
            currentTarget: {
                dataset: {
                    goodsid: goodsid,
                }
            }
        })

    },
    closeSpec() {
        this.setData({
            showSpec: false
        })
    },
    specClick(evt) {
        this.setData({
            currentSpec: evt.currentTarget.dataset.index
        })
    },
    submitSpec(evt) {
        let goods_id = evt.currentTarget.dataset.goodsid
        let {
            num = 1, cid = 0, cartNum = 0, currentSpec = null, specList = [], currentGoods = {}, currentGoodsIndex = 0
        } = this.data
        let cart_quantity = this.data.list[currentGoodsIndex].cart_quantity
        if (specList != 0 && currentSpec == null) {
            wx.showToast({
                icon: 'none',
                title: '请选择规格',
            })
            return
        }
        if (!cid) return
        wx.showLoading({
            title: '请稍等...',
        })

        let params = {
            goods_id: specList.length != 0 ? specList[currentSpec].goods_id : goods_id,
            quantity: num,
            sku_id: specList.length != 0 ? specList[currentSpec].id : 0,
            type: 3,
        }
        app.addToCart(params).then(res => {
            wx.hideLoading()
            cart_quantity++
            this.setData({
                showSpec: false,
                currentSpec: null,
                specList: [],
                [`list[${currentGoodsIndex}].cart_quantity`]: cart_quantity
            })
            wx.showToast({
                icon: 'none',
                title: '添加购物车成功,等你来买',
            })
        }).catch(err => {
            wx.hideLoading()
            this.setData({
                showSpec: false,
                currentSpec: null,
                specList: [],
            })
        })
    },
    bindStatus(e) {
        let sort = this.data.sort //当前sort
        let status = e.currentTarget.dataset.status
        if (sort == 'DESC') { //如果为升序，设置为降序
            sort = 'ASC'
        } else {
            sort = 'DESC'
        }
        const tab = this.tab()
        tab.page = 1
        tab.loading = false
        tab.nextPage = true
        tab.list = []
        this.setData(tab)
        this.setData(Object.assign({
            status,
            sort,
        }, tab))

        this.loadGoods()
    },
    toDetail(evt) {
        let id = evt.currentTarget.dataset.id
        this.setData({
            isClose: false,
            compareCid: this.data.cid
        })
        wx.navigateTo({
            url: './goods-detail?cid=' + this.data.cid + '&goods_id=' + id
        })
    },
    onUnload() {
        setTimeout(() => {
            this.setData({
                isClose: true
            })
        }, 200)
    },
    onHide() {
        if (this.data.isClose) {
            console.log('重新打开')
        }
    },
})